/*
 * ------------------------------------------------------------------
 * 加密模块
 * ------------------------------------------------------------------
 * @关于我：
 * QQ:2815473064
 * wechat:13531609457
 * ------------------------------------------------------------------
 */

const Crypto = require("crypto-js");
const CONFIG = require("../config");
const crpytoConfig = CONFIG.crypto;
const config = {
  AES_KEY: crpytoConfig.AES_KEY, // 秘钥
  AES_IV: crpytoConfig.AES_IV, // 偏移量
  AES_MODE: Crypto.mode.CBC, // 加密模式
  AES_PADDING: Crypto.pad.Pkcs7,
};
// 加密
function encrypt(value) {
  if (value) {
    const { AES_IV, AES_KEY, AES_MODE, AES_PADDING } = config;
    const key = Crypto.enc.Utf8.parse(AES_KEY);
    const iv = Crypto.enc.Utf8.parse(AES_IV);
    let value_parse_utf8 = Crypto.enc.Utf8.parse(value);
    let toValue = Crypto.AES.encrypt(value_parse_utf8, key, {
      iv,
      mode: AES_MODE,
      padding: AES_PADDING,
    });
    return toValue.toString();
  } else {
    return "";
  }
}
// 解密
const decrypt = (value) => {
  const { AES_IV, AES_KEY, AES_MODE, AES_PADDING } = config;
  const key = Crypto.enc.Utf8.parse(AES_KEY);
  const iv = Crypto.enc.Utf8.parse(AES_IV);
  let decrypt = Crypto.AES.decrypt(value, key, {
    iv,
    mode: AES_MODE,
    padding: AES_PADDING,
  });
  return decrypt.toString(Crypto.enc.Utf8);
};
module.exports = {
  encrypt,
  decrypt,
};
